/*
 * @Author: sxb
 * @Email: sxb@mail.com
 * @Date: 2020-02-19 11:52:57
 * @Descripttion: 
 */
import { Component, OnInit } from '@angular/core';
import { NzFormatEmitEvent, NzTreeHigherOrderServiceToken } from 'ng-zorro-antd/core';
import { FormBuilder, FormControl, FormGroup, Validators, ValidatorFn, AbstractControl } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { MaterialRelationService } from './material-relation.service';
import { HCommonService } from 'src/app/h-common/h-common.service';

export function whsAreaValidator(nameRe: RegExp): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} | null => {
        const forbidden = nameRe.test(control.value);
        return forbidden ? null : {'whsAreaValidator': {value: control.value}};
    };
  }

@Component({
    selector: 'app-material-relation',
    templateUrl: './material-relation.component.html',
    styleUrls: ['./material-relation.component.scss']
})
export class MaterialRelationComponent implements OnInit {

    selField = "all";
    selWhere = "all";
    bornRoles = {};

    selFieldList = [{value:"all", text:"全部"},{value:"jack", text:"Jack"},{value:"lucy", text:"Lucy"}];//查询字段数据
    selWhereList = [{value:"all", text:"全部"},{value:"jack", text:"Jack"},{value:"lucy", text:"Lucy"}];//查询条件数据    
    selWhsTree = []; // 仓库树
    nodes = [];

    //--弹出框 
    isVisible = false;
    isOkLoading = false;
    
    validateForm: FormGroup;

    hidWarehouseId = ''; 
    hidWhsAreaId = '';
    hidMatetialId = '';

    whsAreaChange($event): void {
        if(/^\d+-\d+$/.test($event)){
            let whsAndArea = $event.split("-");
            if(whsAndArea.length < 2){
                this.message.warning("库房&库区数据有误！");
            }
            this.hidWarehouseId = whsAndArea[0];
            this.hidWhsAreaId = whsAndArea[1];
        }
    }
    // aaa($event): void{
    //     console.log($event);
    // }

    showModal(): void {
        this.isVisible = true;
        this.validateForm.reset();  
        this.hidWarehouseId = '';
        this.hidWhsAreaId = '';
        this.hidMatetialId = '';
        if(this.whsAreaId != ""){
            this.hidWarehouseId = this.warehouseId;
            this.hidWhsAreaId = this.whsAreaId;
            this.validateForm.patchValue({
                whsArea: this.warehouseId +"-"+ this.whsAreaId
            });
        }
    }

    handleOk(): void {
        this.isOkLoading = true;
        setTimeout(() => {
            this.isOkLoading = false;
        }, 1000);
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
        if (this.validateForm.status == "VALID") {
            //this.postMaterialRelation();
        }
    }

    handleCancel(): void {
        this.isVisible = false;
        this.isOkLoading = false;
    }

     //--弹出物料选择框  
  txtAltMatCode: any = '';
  txtAltMatName: any = '';

  isMatVisible: Boolean = false;
  isMatOkLoading: Boolean = false;
  altMatPageIndex: any = '1';//table当前页
  altMatPageSize: any = '8';//table每页条数
  altMatTotalSize: any = '';//总共条数
  altMatListOfData  = [];
  selMaterialObj = {};
  // table页码点击事件
  altMatClickPage(current) {
    this.altMatPageIndex = current
    this.getAltMaterialData()
  }
  async getAltMaterialData() {
    let data = {
        code: this.txtAltMatCode,
        name: this.txtAltMatName,
        page: this.altMatPageIndex - 1 < 0 ? 0 : this.altMatPageIndex - 1,
        size: this.altMatPageSize
    }
    let list: any = await this.relationService.getMaterialList(data).subscribe(res => {
      res.content.forEach(item => {
          item.checked = false;
      })
      this.altMatTotalSize = res.totalElements
      this.altMatListOfData = res.content;
    });
  }
  getAltMatSearchData(){
    this.altMatPageIndex = 1;
    this.getAltMaterialData();
  }
  showMatModal(): void {
    if (this.whsAreaId == '') {
        this.message.warning("请先选择库房-库区！");
        return;
    }else{
        this.getAltMaterialData();
        this.isMatVisible = true;
    }
  }
  matHandleOk(): void {
    let materialIds = [];
    this.altMatListOfData.forEach(item => {
        if (item.checked) {
            materialIds.push(item.id)
        }
    });
    this.postMaterialRelation(materialIds)
  }
  matHandleCancel(): void {
    this.isMatVisible = false;
  }

  altMatIsAllChecked = false;
  altMatCheckAll(value: boolean){
    this.altMatListOfData.forEach(item => {
        item.checked = value;
    })
  }
  altMatCheckSingle() {
    let _isAllCheck = true;
    this.altMatListOfData.forEach(item => {
        if (!item.checked) {
            _isAllCheck = false;
        }
    })
    this.isAllChecked = _isAllCheck;
  }

    async postMaterialRelation(materialIds){
        let dataList = [];
        materialIds.forEach(item => {
            dataList.push({ warehouseId:this.warehouseId, warehouseAreaId:this.whsAreaId, materialId:item });
        });
        await this.relationService.postMaterialRelation(dataList).subscribe(res => {
            this.isMatVisible = false;
            this.isMatOkLoading = false;
            this.getAllData();
        })
    } 
    
    async delete(){
        let ids = [];
        this.listOfData.forEach(item=>{
            if(item.checked){
                ids.push(item.id);
            }
        })
        await this.relationService.delMaterialRelations(ids).subscribe(res => {
            if(this.isAllChecked === true){
                this.pageIndex = 1;
                this.isAllChecked = false;
            }
            this.getAllData()
        })
    }
  
    //--分页部分
    pageIndex: any = '1';//table当前页
    pageSize: any = '10';//table每页条数
    totalSize: any = '500';//总共条数
    materialCode = '';
    materialName = '';
    warehouseId = '';
    whsAreaId = '';
    listOfData  = [];
    // table页码点击事件
    clickPage(current) {
        this.pageIndex = current
        this.getAllData()
    }
    async getAllData(){
        
        let data = {
            code: this.materialCode,
            name: this.materialName,
            warehouseId: this.warehouseId,
            warehouseAreaId: this.whsAreaId,
            page: this.pageIndex - 1 < 0 ? 0 : this.pageIndex - 1,
            size: this.pageSize
        }
        await this.relationService.getMaterialRelation(data).subscribe(res => {
            res.content.forEach(item => {
                item.checked = false;
            })
            this.totalSize = res.totalElements
            this.listOfData = res.content;
        })
    }
    getSearchData(){
        this.pageIndex = 1;
        this.getAllData();
    }
    
    isAllChecked = false;
    checkAll(value: boolean): void {
        this.listOfData.forEach(item => {
            item.checked = value;
        })
    }
    checkSingle() {
        let _isAllCheck = true;
        this.listOfData.forEach(item => {
            if (!item.checked) {
                _isAllCheck = false;
            }
        })
        this.isAllChecked = _isAllCheck;
      }

    constructor(
        private message: NzMessageService,
        private relationService : MaterialRelationService,
        private fb: FormBuilder,
        private commonService : HCommonService
    ) { }

    ngOnInit(): void {
        /* 获取权限 */
        this.bornRoles = this.commonService.getRoles("stock");

        this.validateForm = this.fb.group({
            whsArea: [null, [Validators.required, whsAreaValidator(/^\d+-\d+$/)]],
            material: [null, [Validators.required]]
            // quantity: [null, [Validators.required]],
            // buyCycle: [null, [Validators.required]],
            // maxQuty: [null, [Validators.required]],
            // normalQuty: [null, [Validators.required]]
          })

        this.getAllData()
        this.getNodes()
    }
    
    // 获取左侧树状结构
    async getNodes() {
        await this.relationService.getWhsTree().subscribe(res => {
            var newList = res;
            var selWhsList = res;
            for (let i = 0; i < newList.length; i++) {
                newList[i] = {
                    key: newList[i].id,
                    title: newList[i].name,
                    isLeaf: newList[i].warehouseAreas.length > 0 ? false : true,
                    children: newList[i].warehouseAreas || []
                }
                if (newList[i].children && newList[i].children != '') {
                    //newList[i].isLeaf = false
                    let children1 = newList[i].children
                    for (let a = 0; a < children1.length; a++) {
                        children1[a] = {
                            key: newList[i].key + "-" + children1[a].id,
                            pid: newList[i].key,
                            pname: newList[i].title,
                            title: children1[a].name,
                            isLeaf: true
                        }
                    }
                }
            }
            let nodes = [];
            nodes[0] = {key:0, title:"仓库", isLeaf: false, expanded: true, children: newList};
            this.nodes = nodes;
            this.selWhsTree = newList;
        })
    }
    nzEvent(event: NzFormatEmitEvent): void {
        let nodeObj = event.node.origin;
        if(nodeObj.isLeaf != true){
            if(nodeObj.key == "0"){
                this.warehouseId = '';
                this.whsAreaId = '';
            }else{
                this.warehouseId = nodeObj.key;
                this.whsAreaId = '';
            }
        }else{
           let conIs=nodeObj.key.toString().indexOf("-");
           if(conIs==-1)
           {
            this.whsAreaId = "0";
            this.warehouseId="0";
           }
           else
           {
            let whsAndArea = nodeObj.key.split("-");
            if(whsAndArea.length < 2){
                this.message.warning("库房&库区数据有误！");
            }
            this.warehouseId = whsAndArea[0];
            this.whsAreaId = whsAndArea[1];
           }
        }
        this.pageIndex = 0;
        this.pageSize = 10;
        this.getAllData();
    }

}
